package com.zzyy.study.aop;

import com.zzyy.study.annotation.ServiceSwitch;
import com.zzyy.study.constant.Constant;
import com.zzyy.study.resp.ResultData;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @auther zzyy
 * @create 2024-01-13 18:49
 */
@Aspect
@Component
@Slf4j
public class ServiceSwitchAOP {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Around("@annotation(com.zzyy.study.annotation.ServiceSwitch)")
    public Object around(ProceedingJoinPoint point) {
        Object[] args = point.getArgs();// 获取被代理的方法的参数
        Object target = point.getTarget();// 获取被代理的对象
        MethodSignature signature = (MethodSignature) point.getSignature();// 获取通知签名

        try
        {
            // 获取被代理的方法
            Method method = target.getClass().getMethod(signature.getName(), signature.getParameterTypes());
            // 获取方法上的注解
            ServiceSwitch annotation = method.getAnnotation(ServiceSwitch.class);
            // 核心业务逻辑
            if (annotation != null)
            {
                String switchKey = annotation.switchKey();
                String message = annotation.message();
                String configVal = stringRedisTemplate.opsForValue().get(switchKey);
                if (Constant.SWITCHCLOSE.equals(configVal)) {
                    // 开关关闭说明值等于零，则返回提示。
                    return ResultData.fail(HttpStatus.FORBIDDEN.value()+"", message);
                }
            }
            // 放行
            return point.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}























/**
 * 定义切点，使用了@ServiceSwitch注解的类或方法都拦截
 */
    /*
    @Pointcut("@annotation(com.zzyy.study.annotation.ServiceSwitch)")
    public void pointcut() { }
    */